package vworld.dao.room;

import generated.domain.avatar.Avatar;
import generated.domain.room.Room;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import vworld.dao.HibernateUtil;

public class RoomDAO {

	public void createRoom(Room pRoom) {
		Transaction tx = null;
		Session session = HibernateUtil.currentSession();
		try {
			tx = session.beginTransaction();
			session.save(pRoom);
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			if (tx != null && tx.isActive())
				tx.rollback();
		} finally {
			HibernateUtil.closeSession();
		}
	}

	public void deleteRoom(Room pRoom) {
		Transaction tx = null;
		Session session = HibernateUtil.currentSession();
		try {
			tx = session.beginTransaction();
			session.delete(pRoom);
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			if (tx != null && tx.isActive())
				tx.rollback();
		} finally {
			HibernateUtil.closeSession();
		}
	}

	public void saveOrUpdateRoom(Room pRoom) {
		Transaction tx = null;
		Session session = HibernateUtil.currentSession();
		try {
			tx = session.beginTransaction();
			// session.saveOrUpdate(pRoom.getInsideAvatars());
			session.saveOrUpdate(pRoom);
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			if (tx != null && tx.isActive())
				tx.rollback();
		} finally {
			HibernateUtil.closeSession();
		}
	}

	public Room getRoom(String pName) {
		try {
			Session session = HibernateUtil.currentSession();
			Query query = session
					.createQuery("from Room r where r.name = :name");
			query.setString("name", pName);

			for (Object obj : query.list()) {
				return (Room) obj;
			}
			return null;
		} finally {
			HibernateUtil.closeSession();
		}
	}

	public Avatar[] getInsideAvatars(String pRoomName) {
		try {
			Session session = HibernateUtil.currentSession();
			Query query = session
					.createQuery("select insideAvatars from Room r where r.name = :name");
			query.setString("name", pRoomName);

			return (Avatar[]) query.list().toArray(
					new Avatar[query.list().size()]);
		} finally {
			HibernateUtil.closeSession();
		}
	}
}
